﻿using System;
using System.Linq;

using MiniSched.Data;
using MiniSched.Web.Areas.Api.V0.Models;

namespace MiniSched.Web.Areas.Api.V0.Controllers {

    public class MarketMessageSubscriptionController : EntityApiController<MarketMessageSubscription, MarketMessageSubscriptionRequestModel> {

        internal override MarketMessageSubscription Create(MarketMessageSubscription model) {

            var c = Context;
            var subscriber = model.EmailAddress.Address;
            var messageType = model.MarketMessage.OptionName;

            var emailAddresses = c.EmailAddresses;
            var emailAddress = emailAddresses.FirstOrDefault(a => a.Address == subscriber);
            if (emailAddress == null) {
                emailAddresses.Add(emailAddress = new EmailAddress {
                    Address = subscriber
                });
            }

            var marketMessages = c.MarketMessages;
            var marketMessage = marketMessages.FirstOrDefault(m => m.OptionName == messageType);
            if (marketMessage == null) {
                marketMessages.Add(marketMessage = new MarketMessage {
                    OptionName = messageType
                });
            }

            var marketMessageSubscriptions = c.MarketMessageSubscriptions;
            var marketMessageSubscription = marketMessageSubscriptions.FirstOrDefault(s =>
                (s.EmailAddressId == emailAddress.Id) &&
                (s.MarketMessageId == marketMessage.Id)
            );
            if (marketMessageSubscription == null) {
                marketMessageSubscriptions.Add(marketMessageSubscription = new MarketMessageSubscription {
                    EmailAddressId = emailAddress.Id,
                    MarketMessageId = marketMessage.Id
                });
            }

            return marketMessageSubscription;
        }
    }
}
